package www.webols.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

import android.util.Log;


public class Weibo {
	public static final String API_ROOT="https://api.weibo.com";
	public static final String TOKEN_URI="/oauth2/access_token";
	public static final String PARAM_CLIENT_ID="client_id";
	public static final String PARAM_CLIENT_SECRET="client_secret";
	public static final String PARAM_GRANT_TYPE="grant_type";
	public static final String PARAM_CODE="code";
	public static final String PARAM_REDIRECT_URI="redirect_uri";
	public String getToken(String code){
		
		Map<String,String> params=new HashMap<String,String>();
		params.put(PARAM_CLIENT_ID, StringUtil.WEIBO_APP_KEY);
		params.put(PARAM_CLIENT_SECRET,StringUtil.WEIBO_APP_SECRET);
		params.put(PARAM_GRANT_TYPE, "authorization_code");
		params.put(PARAM_REDIRECT_URI,StringUtil.WEIBO_REDIRECT_URL);
		params.put(PARAM_CODE,code);
		
				
		
		String strUrl=API_ROOT+TOKEN_URI;
		Log.d("token_url:",strUrl);
		Log.d("code: ",code);
		HttpsUtils utils=new HttpsUtils();
		String result=utils.run(strUrl,params);//this.getData(strUrl,"POST",params);
		return result;
	}
	
	public String getData(String url, String method ,Map<String,String> params) {
		String returns = "";

		// Step One register scheme of https
		SSLContext ctx = null;
		X509TrustManager tm = null;
		try {
			ctx = SSLContext.getInstance("TLS");
			tm = new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void checkServerTrusted(X509Certificate[] arg0,
						String arg1) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				} 
				
			};
			ctx.init(null, new TrustManager[]{tm}, null); 
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
		X509HostnameVerifier v=(X509HostnameVerifier) hostnameVerifier;

		SchemeRegistry registry = new SchemeRegistry();
		CustomSSLSocketFactory socketFactory=null;
		try {
			socketFactory = new CustomSSLSocketFactory();
		} catch (KeyManagementException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnrecoverableKeyException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (KeyStoreException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		//ctx.getSocketFactory().
		registry.register(new Scheme("https", socketFactory, 443));
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

		// Step Two Get httpClient and httpPost

		DefaultHttpClient client = new DefaultHttpClient();
		SingleClientConnManager mgr = new SingleClientConnManager(
				client.getParams(), registry);
		DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
				client.getParams());
		// ------- Set verifier
		HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
		HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory.getFACTORY());
		// -------Example send http request
		// final String url =
		// "https://martinreichart.com/_tmpdata/login_valid.json";
		HttpGet httpGet = new HttpGet(url);
		HttpPost httpPost=new HttpPost(url);
		
		Iterator<String> keys= params.keySet().iterator();
		while(keys.hasNext()){
			String key=keys.next();
			
			httpPost.addHeader(key, params.get(key));
		}
		try {
			HttpResponse resp=httpClient.execute(httpPost);
			
			returns=read(resp);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returns;
	}
	
	 private static String read(HttpResponse response) throws WeiboException{
	    	String result = "";
	    	HttpEntity entity = response.getEntity();
			InputStream inputStream;
			try {
				inputStream = entity.getContent();
				ByteArrayOutputStream content = new ByteArrayOutputStream();
		
				Header header = response.getFirstHeader("Content-Encoding");
				if (header != null && header.getValue().toLowerCase().indexOf("gzip") > -1) {
					inputStream = new GZIPInputStream(inputStream);
				}
		
				// Read response into a buffered stream
				int readBytes = 0;
				byte[] sBuffer = new byte[512];
				while ((readBytes = inputStream.read(sBuffer)) != -1) {
					content.write(sBuffer, 0, readBytes);
				}
				// Return result from buffered stream
				result = new String(content.toByteArray());
		    	return result;
			} catch (IllegalStateException e) {
				throw new WeiboException(e);
			} catch (IOException e) {
				throw new WeiboException(e);
			}
	    }
}
